package com.wangshouyu.mp.base.request;

import com.google.common.io.ByteStreams;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
/**
 * @author 王守钰
 * @date 2020年12月04日 19:30
 * @description InputStreamBody
 */
public class InputStreamBody implements ResponseBody {

    private final InputStream inputStream;
    private final Integer length;

    public InputStreamBody(InputStream inputStream, Integer length) {
        this.inputStream = inputStream;
        this.length = length;
    }

    public static ResponseBody orNull(InputStream inputStream, Integer length) {
        if (inputStream == null) {
            return null;
        }
        return new InputStreamBody(inputStream, length);
    }

    @Override
    public Integer length() {
        return length;
    }

    @Override
    public boolean repeatable() {
        return false;
    }

    @Override
    public InputStream inputStream() {
        return inputStream;
    }

    @Override
    public Reader reader(Charset charset) throws IOException {
        if(null == charset){
            throw new RuntimeException("charset should not be null");
        }
        return new InputStreamReader(inputStream, charset);
    }

    @Override
    public void close() throws IOException {
        inputStream.close();
    }

    @Override
    public String toString() {
        try {
            return new String(ByteStreams.toByteArray(inputStream), UTF_8);
        } catch (Exception e) {
            return super.toString();
        }
    }
}

